import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { Loading, MessageBox } from 'element-ui';
require('es6-promise').polyfill();

export interface RequestConfig {
    loading: boolean
}

class axiosEx {
    instance: AxiosInstance
    redirect: Boolean

    constructor() {
        var self = this;
        this.redirect = true;
        this.instance = axios.create({
            baseURL: '/gateway/'
        })

        // 请求拦截器
        this.instance.interceptors.request.use(function (request) {
            if (localStorage.getItem('Authorization')) {
                request.headers.Authorization = localStorage.getItem('Authorization');
            }
            return request;
        }, function (error) {
            return Promise.reject(error);
        });

        // 响应拦截器
        this.instance.interceptors.response.use(function (response) {
            if (response.data.status === 4019 || response.data.status === 4018) {
                localStorage.removeItem('Authorization')
                localStorage.removeItem('userInfo')
                if (!(location.pathname.indexOf('index.html') > -1 || location.pathname.indexOf('market.html') > -1 || location.pathname.indexOf('discount.html') > -1 || location.pathname.indexOf('tools.html') > -1)) {
                    if (self.redirect) {
                        self.redirect = false;
                        location.href = `user.html#/?back=${location.pathname.replace(/^\//, '')}${location.hash}`
                    }
                }
            } else if (response.data.status >= 300 && response.data.status !== 4019 && response.data.status !== 4018) {
                // 全局响应拦截（请求失败后，进行拦截）
                MessageBox.alert(response.data.msg, '提示', {
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    callback: action => { }
                })
            }
            return response.data;
        }, function (error) {
            return Promise.reject(error);
        });
    }

    /**
     * 重写 Axios.get 添加 RequestConfig 配置
     * @param url string
     * @param config AxiosRequestConfig
     * @param cfg RequestConfig 自定义配置
     */
    async get(url: string, config?: AxiosRequestConfig, cfg?: RequestConfig) {
        let self = this;
        if (!cfg) {
            var loadingInstance = Loading.service({
                background: 'rgba(255, 255, 255, 0.6)',
                fullscreen: true
            })
        }
        let res = await this.instance.get(url, config);
        return new Promise(function (resolve, reject) {
            if (loadingInstance) loadingInstance.close();
            resolve(res)
        })
    }

    /**
     * 重写 Axios.post 添加 RequestConfig 配置
     * @param url string
     * @param data any
     * @param config AxiosRequestConfig
     * @param cfg RequestConfig 自定义配置
     */
    async post(url: string, data?: any, config?: AxiosRequestConfig, cfg?: RequestConfig) {
        let self = this;
        if (!cfg) {
            var loadingInstance = Loading.service({
                background: 'rgba(255, 255, 255, 0.6)',
                fullscreen: true
            })
        }
        let res = await this.instance.post(url, data, config)
        return new Promise(function (reslove, reject) {
            if (loadingInstance) loadingInstance.close();
            reslove(res)
        })
    }

    /**
     * 重写 Axios.put 添加 RequestConfig 配置
     * @param url string
     * @param data any
     * @param config AxiosRequestConfig
     * @param cfg RequestConfig 自定义配置
     */
    async put(url: string, data?: any, config?: AxiosRequestConfig, cfg?: RequestConfig) {
        let self = this;
        if (!cfg) {
            var loadingInstance = Loading.service({
                background: 'rgba(255, 255, 255, 0.6)',
                fullscreen: true
            })
        }
        let res = await this.instance.put(url, data, config)
        return new Promise(function (reslove, reject) {
            if (loadingInstance) loadingInstance.close();
            reslove(res)
        })
    }

    /**
     * 重写 Axios.delete 添加 RequestConfig 配置
     * @param url string
     * @param config AxiosRequestConfig
     * @param cfg RequestConfig 自定义配置
     */
    async delete(url: string, config?: AxiosRequestConfig, cfg?: RequestConfig) {
        let self = this;
        if (!cfg) {
            var loadingInstance = Loading.service({
                background: 'rgba(255, 255, 255, 0.6)',
                fullscreen: true
            })
        }
        let res = await this.instance.delete(url, config)
        return new Promise(function (reslove, reject) {
            if (loadingInstance) loadingInstance.close();
            reslove(res)
        })
    }

    /**
     * 重写 Axios.patch 添加 RequestConfig 配置
     * @param url string
     * @param data any
     * @param config AxiosRequestConfig
     * @param cfg RequestConfig 自定义配置
     */
    async patch(url: string, data?: any, config?: AxiosRequestConfig, cfg?: RequestConfig) {
        let self = this;
        if (!cfg) {
            var loadingInstance = Loading.service({
                background: 'rgba(255, 255, 255, 0.6)',
                fullscreen: true
            })
        }
        let res = await this.instance.patch(url, config)
        return new Promise(function (reslove, reject) {
            if (loadingInstance) loadingInstance.close();
            reslove(res)
        })
    }

    /**
     * 重写 Axios.request 添加 RequestConfig 配置
     * @param config AxiosRequestConfig
     * @param cfg RequestConfig 自定义配置
     */
    async request(config: AxiosRequestConfig, cfg?: RequestConfig) {
        let self = this;
        if (!cfg) {
            var loadingInstance = Loading.service({
                background: 'rgba(255, 255, 255, 0.6)',
                fullscreen: true
            })
        }
        let res = await this.instance.request(config)
        return new Promise(function (reslove, reject) {
            if (loadingInstance) loadingInstance.close();
            reslove(res)
        })
    }
}

export default new axiosEx();